/*
 * Javadoc2DictView.java
 */

package com.braveo.dict.javadoc;

import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * The application's main frame.
 */
public class Javadoc2DictView extends FrameView {

    public Javadoc2DictView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = Javadoc2DictApp.getApplication().getMainFrame();
            aboutBox = new Javadoc2DictAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        Javadoc2DictApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        btnClassNames = new javax.swing.JButton();
        btnStorageDir = new javax.swing.JButton();
        txtStorageDir = new javax.swing.JTextField();
        btnStore = new javax.swing.JButton();
        btnSaveSql = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        taContent = new javax.swing.JTextArea();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.braveo.dict.javadoc.Javadoc2DictApp.class).getContext().getResourceMap(Javadoc2DictView.class);
        btnClassNames.setText(resourceMap.getString("btnClassNames.text")); // NOI18N
        btnClassNames.setName("btnClassNames"); // NOI18N
        btnClassNames.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClassNamesActionPerformed(evt);
            }
        });

        btnStorageDir.setText(resourceMap.getString("btnStorageDir.text")); // NOI18N
        btnStorageDir.setName("btnStorageDir"); // NOI18N
        btnStorageDir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStorageDirActionPerformed(evt);
            }
        });

        txtStorageDir.setText(resourceMap.getString("txtStorageDir.text")); // NOI18N
        txtStorageDir.setName("txtStorageDir"); // NOI18N

        btnStore.setText(resourceMap.getString("btnStore.text")); // NOI18N
        btnStore.setName("btnStore"); // NOI18N
        btnStore.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStoreActionPerformed(evt);
            }
        });

        btnSaveSql.setText(resourceMap.getString("btnSaveSql.text")); // NOI18N
        btnSaveSql.setName("btnSaveSql"); // NOI18N
        btnSaveSql.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveSqlActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnClassNames)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnStore)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSaveSql))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnStorageDir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtStorageDir, javax.swing.GroupLayout.DEFAULT_SIZE, 303, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnClassNames)
                    .addComponent(btnStore)
                    .addComponent(btnSaveSql))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnStorageDir)
                    .addComponent(txtStorageDir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        taContent.setColumns(20);
        taContent.setRows(5);
        taContent.setName("taContent"); // NOI18N
        jScrollPane1.setViewportView(taContent);

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 410, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(com.braveo.dict.javadoc.Javadoc2DictApp.class).getContext().getActionMap(Javadoc2DictView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 410, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 240, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void btnClassNamesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClassNamesActionPerformed
        ConfigManager cm = ConfigManager.getManager();
        JFileChooser jf = new JFileChooser(cm.getWordDir());
        jf.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int ret = jf.showOpenDialog(this.getFrame());
        if(ret != JFileChooser.APPROVE_OPTION){
            return;
        }
        workDir = jf.getSelectedFile().getAbsolutePath();
        cm.setWorkDir(workDir);

        parseDirectory(workDir,false);

        JOptionPane.showMessageDialog(getFrame(), "Parsed directory " + workDir);
    }//GEN-LAST:event_btnClassNamesActionPerformed

    private void btnStorageDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStorageDirActionPerformed
        ConfigManager cm = ConfigManager.getManager();
        JFileChooser jf = new JFileChooser(cm.getStorageDir());
        jf.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int ret = jf.showSaveDialog(this.getFrame());
        if(ret != JFileChooser.APPROVE_OPTION){
            return;
        }

        storageDir = jf.getSelectedFile().getAbsolutePath();
        txtStorageDir.setText(storageDir);
        cm.setStorageDir(storageDir);
    }//GEN-LAST:event_btnStorageDirActionPerformed

    private void btnStoreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStoreActionPerformed
        DictStorage.getStorage().clearMemory();
        parseDirectory(workDir, true);
        JOptionPane.showMessageDialog(getFrame(), "Saved");
    }//GEN-LAST:event_btnStoreActionPerformed

    private void btnSaveSqlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveSqlActionPerformed
        //DictStorage.getStorage().createSql(storageDir, storageDir);
        JFileChooser jf = new JFileChooser(storageDir);
        if(jf.showSaveDialog(this.getFrame())==JFileChooser.APPROVE_OPTION){
            DictStorage.getStorage().createSql(storageDir, jf.getSelectedFile().getAbsolutePath());
            JOptionPane.showMessageDialog(getFrame(), "Created SQL");
        }

    }//GEN-LAST:event_btnSaveSqlActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClassNames;
    private javax.swing.JButton btnSaveSql;
    private javax.swing.JButton btnStorageDir;
    private javax.swing.JButton btnStore;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTextArea taContent;
    private javax.swing.JTextField txtStorageDir;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
    private Logger logger = Logger.getLogger(Javadoc2DictView.class.getName());
    
    private static final Pattern CLASS_DOC_FILE_NAME_PATTERN = 
            Pattern.compile("([A-Za-z0-9_.]+)\\.html");

    private String storageDir;
    private String workDir;
    
    protected void parseDirectory(String workDir, boolean store){
        logger.info(workDir);
        File file = new File(workDir);

        if(file.getName().equals("class-use"))
            return;

        File[] files = file.listFiles();

        for(File f : files){
            if(f.isDirectory()){
                parseDirectory(f.getAbsolutePath(), store);
            }else{
                String shortName = f.getName();
                logger.info("Get file => " + shortName);
                Matcher m = CLASS_DOC_FILE_NAME_PATTERN.matcher(shortName);
                if(!m.matches())
                    continue;

                String cn = m.group(1);

                logger.info("Ready to parse => " + shortName + " : " + cn);
                String className = parseFileForClassName(f, cn);
                if(className == null)
                    continue;
                if(!store){
                    taContent.append(className + "\n");
                }else{
                    //DictStorage.getStorage().addCrossMapping(cn, className);
                    parseFileForStore(f, cn, className);
                }

            }
        }
    }

    protected String parseFileForClassName(File file, String className){
        logger.info("Parsing file : => " + file.getName() + " class = " + className);
        String result = null;

        FileReader fr = null;
        try{
            String packageName = null;
            //String className = null;
            
            fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String line;
            int stage = 0;
            while((line = br.readLine())!=null){
                //if(stage > 0)
                    //logger.info("stage = " + stage + " : " + line);
                switch(stage){
                    case 0: //just begin:
                    {
                        if(line.startsWith("<!-- ======== START OF CLASS DATA ======== -->"))
                            stage = 1;
                        break;
                    }
                    case 1: //class data
                    {
                        if(line.startsWith("<H2>"))
                            stage ++;
                        else
                            throw new RuntimeException(line);
                        continue;
                    }
                    case 2: //H2
                    {
                        if(line.startsWith("<FONT "))
                            stage ++;
                        else
                            throw new RuntimeException(line);
                        continue;
                    }
                    case 3: //FONT
                    {
                        Pattern p = Pattern.compile("([a-zA-Z.0-9]+)</FONT>");
                        Matcher m = p.matcher(line);
                        if(m.find()){
                             packageName = m.group(1);
                             ++stage;
                        }
                        else
                            throw new RuntimeException(line);
                        continue;
                    }
                    case 4:
                    {
                        if(line.startsWith("<BR>")){
                            ++stage;
                        }else{
                            throw new RuntimeException(line);
                        }
                        continue;

                    }
                    case 5:
                    {
                        Pattern p = Pattern.compile("[a-zA-Z ]+ " + className + ".*");
                        Matcher m = p.matcher(line);
                        if(m.matches()){
                            return packageName + "." + className;
                        }
                        else
                            throw new RuntimeException(line);

                    }
                }

            }
        }catch(IOException ioe){
            logger.warning(ioe.getMessage());
            ioe.printStackTrace();
        }finally{
            if(fr!=null){
                try{
                    fr.close();

                }catch(IOException ioe){
                    
                }
            }
        }

        return result;

    }

    protected void parseFileForStore(File file, String clazzName, String classFullName){
        logger.info("Storing file : => " + file.getName() + " class = " + clazzName);

        DocHelper docHelper = new DocHelper(clazzName, classFullName);

        FileReader fr = null;
        try{
            String packageName = null;
            //String className = null;

            fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String line;
            int stage = 0;
            while((line = br.readLine())!=null){
                //if(stage > 0)
                    //logger.info("stage = " + stage + " : " + line);
                switch(stage){
                    case 0: //just begin:
                    {
                        if(line.startsWith("<!-- ======== START OF CLASS DATA ======== -->"))
                            stage = 1;
                        break;
                    }
                    case 1: //class data
                    {
                        if(line.startsWith("<!-- ========= END OF CLASS DATA ========= -->"))
                            ++stage;
                        else
                            docHelper.addLine(line);
                        break;
                    }
                    case 2:
                    {
                        //DictStorage.getStorage().createContent(storageDir, className, docHelper.parseToDictContent());
                        DictStorage storage = DictStorage.getStorage();
                        storage.addCrossMapping(docHelper.getClazzName(), docHelper.getClazzFullName());
                        storage.createContent(storageDir, docHelper.getClazzFullName(), DocHelper.parseToDictContent(docHelper.getClazzInfo()));
                        Map<String, List<String>> infoMap = docHelper.getDetailInfo();
                        Iterator<String> infoIter = infoMap.keySet().iterator();
                        while(infoIter.hasNext()){
                            String infoKey = infoIter.next();
                            String infoLongKey = new StringBuilder().append(infoKey).append("#").append(docHelper.getClazzFullName()).toString();
                            storage.addCrossMapping(infoKey, infoLongKey);
                            List<String> x = infoMap.get(infoKey);
                            String xc = DocHelper.parseToDictContent(x);                            
                            storage.createContent(storageDir, infoLongKey, xc);
                        }

                        return;
                    }
                }

            }
        }catch(IOException ioe){
            logger.warning(ioe.getMessage());
            ioe.printStackTrace();
        }finally{
            if(fr!=null){
                try{
                    fr.close();

                }catch(IOException ioe){

                }
            }
        }

    }

}
